package middleware

import (
	"auth/authentication"
	"auth/bll"
	log "auth/collector/logger"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// CasbinHandler 拦截器
func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		//if config.Conf.Env != "dev" {
		roles, _ := authentication.ExtractDataFromCtx(c.Request.Context())
		if len(roles.Roles) <= 0 {
			log.Warnf("APP 用户暂未绑定角色，默认放过")
			c.Next()
			return
		}
		//获取请求的PATH
		path := c.Request.URL.Path
		obj := strings.TrimPrefix(path, "")
		// 获取请求方法
		act := c.Request.Method
		// 获取用户的角色
		e := bll.CasbinService.Casbin() // 判断策略中是否存在
		for _, sub := range roles.Roles {
			success, _ := e.Enforce(strconv.Itoa(int(sub)), obj, act)
			if success {
				c.Next()
				return
			}
		}
		c.JSON(http.StatusUnauthorized, "权限不足")
		c.Abort()
		//}
	}
}
